package com.sls.mall.cart.controller;

import com.sls.common.constant.AuthServerConstant;
import com.sls.mall.cart.interceptor.CartInterceptor;
import com.sls.mall.cart.service.CartService;
import com.sls.mall.cart.vo.Cart;
import com.sls.mall.cart.vo.CartItem;
import com.sls.mall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;


@Controller
public class CartController {

    @Autowired
    CartService cartService;

    /**
     * 获取当前用户购物车数据
     */
    @GetMapping("/currentCartItems")
    @ResponseBody
    public List<CartItem> getCurrentCartItems(){
        return cartService.getCurrentCartItems();
    }

    @GetMapping("/cart.html")
    public String toCart(Model model) throws ExecutionException, InterruptedException {
        Cart cart = cartService.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }

    /**
     * 添加购物车
     */
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        cartService.saveCart(skuId,num);
        redirectAttributes.addAttribute("skuId", skuId);
        return "redirect:http://cart.slsmall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartPage(@RequestParam("skuId") Long skuId, Model model){
        CartItem cartItem = cartService.getCartItem(skuId);
        model.addAttribute("item", cartItem);
        return "success";
    }
}
